package top.abrsm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.abrsm.entity.AreaEntity;
import top.abrsm.mapper.AreaMapper;
import top.abrsm.service.IAreaService;
import top.abrsm.util.StateEnum;
import top.abrsm.util.StateException;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, AreaEntity> implements IAreaService {

    @Resource
    private AreaMapper areaMapper;

    @Override
    public List<AreaEntity> queryList (AreaEntity areaEntity) {
        QueryWrapper<AreaEntity> queryWrapper = new QueryWrapper<> ();
        if ( areaEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( areaEntity.getLevel () != null ) {
            queryWrapper.eq ( "level", areaEntity.getLevel () );
        }
        if ( StringUtils.isNotBlank ( areaEntity.getParentId () ) ) {
            queryWrapper.eq ( "parentId", areaEntity.getParentId () );
        }
        List<AreaEntity> areaEntities = baseMapper.selectList ( queryWrapper );
        return areaEntities;
    }

    @Override
    public Integer count (AreaEntity areaEntity) {
        QueryWrapper<AreaEntity> queryWrapper = new QueryWrapper<> ();
        if ( areaEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( areaEntity.getLevel () != null ) {
            queryWrapper.eq ( "level", areaEntity.getLevel () );
        }
        if ( StringUtils.isNotBlank ( areaEntity.getParentId () ) ) {
            queryWrapper.eq ( "parentId", areaEntity.getParentId () );
        }
        Integer integer = baseMapper.selectCount ( queryWrapper );
        return integer;
    }

    @Override
    public AreaEntity saveSingle (AreaEntity areaEntity) {
        if ( areaEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( StringUtils.isBlank ( areaEntity.getId () ) ) {
            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
        }
        areaEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( areaEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return areaEntity;
    }

    @Override
    public List<AreaEntity> queryChild (AreaEntity areaEntity) {
        List<AreaEntity> areaEntities = areaMapper.queryChild ( areaEntity.getParentId (), areaEntity.getLevel () );
        return areaEntities;
    }

    @Override
    public Integer childCount (AreaEntity areaEntity) {
        Integer integer = areaMapper.queryCount ( areaEntity.getParentId (), areaEntity.getLevel () );
        return integer;
    }

}
